import { Industry } from "@/api";
import dayjs, { Dayjs } from "dayjs";

type RangeValue = [Dayjs, Dayjs] | [string, string];

/**
 * Emum Conversion
 */
export function convertEnumToOptions(
  enumObj: any,
  isNorestrictions: boolean = false
): { label: string; value: number }[] {
  const result: { label: string; value: number; disabled: boolean }[] =
    isNorestrictions
      ? [
          {
            disabled: true,
            label: "不限",
            value: undefined as any,
          },
        ]
      : [];

  // Get all numeric values from the enum
  const numericValues = Object.values(enumObj).filter(
    (value) => typeof value === "number"
  );

  for (const value of numericValues) {
    // Get the corresponding key for the numeric value
    const key = enumObj[value] as string;
    result.push({
      disabled: false,
      label: key,
      value: value as number,
    });
  }

  return result;
}

/**
 * phone Conversion
 */
export function formatPhoneNumberStrict(phoneNumber: string | number): string {
  const numStr = phoneNumber.toString();
  if (!/^\d{11}$/.test(numStr)) {
    return `-- (错误手机号)`;
  }
  return `${numStr.substring(0, 3)}****${numStr.substring(7)}`;
}

/**
 * Search Params
 * Picker Time Conversion
 */
export function convertTimeChange(
  time?: RangeValue,
  type: string = "YYYY-MM-DD hh:mm:ss"
) {
  if (time) {
    let startTime = dayjs(time[0], type).format(type);
    let endTime = dayjs(time[1], type).format(type);
    return { startTime, endTime };
  } else {
    return { startTime: undefined, endTime: undefined };
  }
}

/**
 * Result
 * Time Conversion
 */
export function convertTime(time?: any, type: string = "YYYY-MM-DD hh:mm:ss") {
  if (time) {
    return dayjs(time, type).format(type);
  } else {
    return "--";
  }
}

/**
 * Result
 * IndustryList Conversion
 */
export function buildTree(data: Industry[]) {
  // 创建ID到节点的映射
  const map = {} as any;
  // 初始化结果数组
  const result = [] as any;

  // 第一遍遍历：创建映射并初始化children
  data.forEach((item) => {
    if (item.id === undefined) return;
    map[item.id] = {
      ...item,
      children: [],
    };
  });

  // 第二遍遍历：构建树形结构
  data.forEach((item) => {
    if (item.id === undefined) return;
    const node = map[item.id];

    if (item.parentId === 0) {
      // 根节点直接加入结果
      result.push(node);
    } else {
      // 子节点加入父节点的children
      if (item.parentId === undefined) return;
      const parent = map[item.parentId];
      if (parent) {
        parent.children.push(node);
      }
    }
  });

  return result;
}
